package com.chensi.handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.chensi.common.AjaxJson;
import com.google.gson.Gson;


/**
 * 注意若当在spring.xml配置了SimpleMappingExceptionResolver，则不用该方法
 * 
 * @author Chason
 * @version 2016-1-7 下午5:33:23
 */
public class MyExceptionHandler extends SimpleMappingExceptionResolver
{
	private static final Logger log=Logger.getLogger(MyExceptionHandler.class);
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
	{
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		ResponseBody body = handlerMethod.getMethodAnnotation(ResponseBody.class); // 判断有没有@ResponseBody的注解没有的话调用父方法
		if (body == null) {
			request.setAttribute("exception", exception);
			if (exception instanceof IOException) {
				log.error("全局异常处理器捕捉到异常: " + exception.getMessage());
				return new ModelAndView("redirect:/page/error/exception");
			} else if (exception instanceof SQLException) {
				log.error("全局异常处理器捕捉到异常: " + exception.getMessage());
				return new ModelAndView("redirect:/page/error/exception");
			}
			log.error("全局异常处理器捕捉到异常: " + exception.getMessage());
			return new ModelAndView("redirect:/page/error/exception");
		}
		// 设置状态码,注意这里不能设置成500，设成500JQuery不会出错误提示
		// 并且不会有任何反应
		response.setStatus(HttpStatus.OK.value());
		// 设置ContentType
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		// 避免乱码
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		try {
			log.error("全局异常:" + exception.toString());
			exception.printStackTrace();
			PrintWriter writer = response.getWriter();
			writer.write(new Gson().toJson(AjaxJson.getFailInfo()));
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new ModelAndView();
	}
}
